#!/bin/sh

export DOCKER_BUILDKIT=1
export COMPOSE_DOCKER_CLI_BUILD=1

base_files="-f docker-compose.yaml -f docker-compose.postgres.yaml"

# No RPC URL provided, default to Devnet
if [ -z "$WSURL" ] && [ -z "$HTTPURL" ]; then
  # Allow for choosing between geth or parity
  if [ "$GETH_MODE" ]; then
    export CHAIN_ID=1337
    base_files="$base_files -f docker-compose.gethnet.yaml"
  else
    base_files="$base_files -f docker-compose.paritynet.yaml"
  fi
fi

args="node"

if [ "$WITH_OBSERVABILITY" ]; then
    base_files="$base_files -f docker-compose.observability.yaml"
    args="$args grafana"
fi

base="docker compose $base_files"
dev="$base -f docker-compose.dev.yaml"

configure() {
  if [ -z "$CHAIN_ID" ]; then
    export CHAIN_ID=34055
  fi

  if [ -z "$WSURL" ]; then
    export WSURL="ws://devnet:8546"
  fi

  if [ -z "$HTTPURL" ]; then
    export HTTPURL="http://devnet:8545"
  fi

  sed -e "s/SET_CHAIN_ID/$CHAIN_ID/" \
    -e "s,SET_WSURL,$WSURL," \
    -e "s,SET_HTTPURL,$HTTPURL," \
    config.toml.tmpl > config.toml
}

clean_docker() {
  $base down -v --remove-orphans
  $dev down -v --remove-orphans
  rm -rf config.toml
}

usage() {
  echo "compose -- A helper script for running common docker-compose commands\

Commands:
    help                  Displays this help menu
    clean                 Remove any containers and volumes related to compose files
    logs                  Display the logs of any service(s) by name
    dev                   Runs the chainlink node container in dev mode
    connect               Connect to chainlink node container
    up                    Run the chainlink cluster with base config
    eth:restart           Reset blockchain data to genesis state
    db:restart            Reset chainlink database"
}

case "$1" in
help)
  usage
  ;;
clean)
  clean_docker
  ;;
logs)
  $base logs -f "${@:2}"
  ;;
dev)
  configure
  $dev build
  $dev up -d $args
  $dev watch --no-up node
  ;;
connect)
  docker exec -it chainlink-node bash
  ;;
up)
  configure
  $base up
  ;;
eth:restart)
  $base rm --force --stop devnet
  if [ "$GETH_MODE" ]; then
    docker volume rm --force docker_geth-db-data
  else
    docker volume rm --force docker_parity-db-data
  fi
  $base up -d devnet
  ;;
db:restart)
  $base stop node
  $base rm --force --stop node-db
  docker volume rm --force docker_node-db-data
  ./compose eth:restart
  $base start node
  ;;
esac
